//
//  UIView+HUD.swift
//  Scanread
//
//  Created by Macintosh on 2023/6/22.
//

import Foundation
import PKHUD

public enum HUDToastType {
    case normal
    case success
    case fail
    case warning
    case custom(UIImage)
}

public extension HUDToastType {
    var image: UIImage? {
        switch self {
        case .normal:
            return nil
        case .success:
            return UIImage(named: "toast_success")
        case .fail:
            return UIImage(named: "toast_fail")
        case .warning:
            return UIImage(named: "toast_warning")
        case .custom(let image):
            return image
        }
    }
}

public extension HUD {
    static func toast(_ type: HUDToastType = .normal, msg: String?, onView view: UIView? = nil, time: Double = 2.5, canTouch: Bool = false, finishedBlock: (() -> Void)? = nil) {
        Async.main {
            guard let msg = msg else {return}
            
            let msgSize = (msg as NSString).boundingRect(with: CGSize(width: UIScreen.main.bounds.width - 100, height: 300),
                                                         options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                         attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 12)],
                                                         context: nil)
            
            let contentView = UIView()
            contentView.backgroundColor = UIColor(valueRGB: 0xAEADAB, alpha: 1.0)
            
            let label = UILabel()
            label.numberOfLines = 0
            label.textAlignment = .center
            label.textColor = UIColor.black
            label.font = UIFont.systemFont(ofSize: 12)
            label.text = msg
            contentView.addSubview(label)
            
            let left = NSLayoutConstraint(item: label,
                                          attribute: .left,
                                          relatedBy: .equal,
                                          toItem: contentView,
                                          attribute: .left,
                                          multiplier: 1.0,
                                          constant: 12)
            let right = NSLayoutConstraint(item: label,
                                           attribute: .right,
                                           relatedBy: .equal,
                                           toItem: contentView,
                                           attribute: .right,
                                           multiplier: 1.0,
                                           constant: -12)
            let centerY = NSLayoutConstraint(item: label,
                                             attribute: .centerY,
                                             relatedBy: .equal,
                                             toItem: contentView,
                                             attribute: .centerY,
                                             multiplier: 1.0,
                                             constant: 0)
            let centerX = NSLayoutConstraint(item: label,
                                             attribute: .centerX,
                                             relatedBy: .equal,
                                             toItem: contentView,
                                             attribute: .centerX,
                                             multiplier: 1.0,
                                             constant: 0)
            label.translatesAutoresizingMaskIntoConstraints = false
            
            let icon = UIImageView()
            icon.image = type.image
            contentView.addSubview(icon)
            
            let iconLeft = NSLayoutConstraint(item: icon,
                                              attribute: .left,
                                              relatedBy: .equal,
                                              toItem: contentView,
                                              attribute: .left,
                                              multiplier: 1.0,
                                              constant: 12)
            let iconCenterY = NSLayoutConstraint(item: icon,
                                                 attribute: .centerY,
                                                 relatedBy: .equal,
                                                 toItem: contentView,
                                                 attribute: .centerY,
                                                 multiplier: 1.0,
                                                 constant: 0)
            let iconright = NSLayoutConstraint(item: icon,
                                               attribute: .right,
                                               relatedBy: .equal,
                                               toItem: label,
                                               attribute: .left,
                                               multiplier: 1.0,
                                               constant: -8)
            let iconW = icon.widthAnchor.constraint(equalToConstant: 24)
            let iconH = icon.heightAnchor.constraint(equalToConstant: 24)
            icon.translatesAutoresizingMaskIntoConstraints = false
            
            if let _ = type.image {
                label.numberOfLines = 1
                label.textAlignment = .left
                NSLayoutConstraint.activate([iconLeft, iconCenterY, iconW, iconH, iconright, right, centerY])
                contentView.frame = CGRect(x: 0,
                                           y: 0,
                                           width: min(msgSize.width + 60, UIScreen.main.bounds.width - 100),
                                           height: 42)
            }else {
                NSLayoutConstraint.activate([left, right, centerX, centerY])
                contentView.frame = CGRect(x: 0, y: 0, width: msgSize.width + 25, height: msgSize.height + 25)
            }
            PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = true
            HUD.dimsBackground = canTouch
            HUD.flash(.customView(view: contentView), onView: view, delay: time) { complete in
                if complete {
                    finishedBlock?()
                }
            }
        }
    }
    
    static func pt_show(_ view: UIView? = nil, _ title: String? = nil, _ subtitle: String? = nil) {
        Async.main {
            let progressView = PTHUDProgressView(title: title, subtitle: subtitle)
            progressView.title = title
            progressView.frame = CGRect(x: 0, y: 0, width: title.or("").isEmpty ? 65 : 100, height: title.or("").isEmpty ? 65 : 100)
            progressView.backgroundColor = UIColor(white: 0, alpha: 0.56)
            PKHUD.sharedHUD.contentView = progressView
            PKHUD.sharedHUD.show(onView: nil)
            PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = false
        }
    }
    
    static func pt_hide() {
        Async.main {
            HUD.hide()
        }
    }
}


// MARK: - UIView+HUD

private let tipsTime = 1.0
public extension UIView {
    // 弹出hud如网络请求等，无标题
    func showHUD( _ title: String? = nil, _ subtitle: String? = nil) {
        /// UI暂时无法提供好的UI输出，建议先使用MBProgressHUD代替，后期再替换过来
        HUD.pt_show(self, title, subtitle)
    }

    // 隐藏hud
    func hideHUD(_ animated: Bool = true) {
        HUD.pt_hide()
    }
  

    // 如果text 为nil则不会弹窗直接return
    func showTips(_ text: String? = nil, type: TipsType = .none, time: Double = 2.5, canTouch: Bool = false, _ finishedBlock: (() -> Void)? = nil) {
        guard let tips = text, tips.count > 0 else {
            return
        }

        HUD.hide(animated: false)
        var hudType: HUDToastType = .normal
        switch type {
            case .none:
                hudType = .normal
            case .successfully:
                hudType = .success
            case .info:
                hudType = .warning
            case .failed:
                hudType = .fail
        }
        HUD.toast(hudType, msg: tips, onView: self, time: time, canTouch: canTouch, finishedBlock:finishedBlock)
    }

    // 用于网络请求：text如果为空则会默认替换为  "服务器开小差了，请稍后再试。"
    func showError(_ text: String? = nil, type: TipsType = .none, _ finishedBlock: (() -> Void)? = nil) {
        let tips = text.or("").count > 0 ? text : "服务器开小差了，请稍后再试。"
        self.showTips(tips, type: type, finishedBlock)
    }
}


//MARK: - UIView+HUD

public enum TipsType {
    case successfully
    case failed
    case info
    case none
}
 
public extension UIViewController {
    func showHUD( _ title: String? = nil, _ subtitle: String? = nil) {
        Async.main {
            self.view.showHUD(title, subtitle)
        }
    }
    
    func hideHUD() {
        Async.main {
            self.view.hideHUD()
        }
    }

    func showTips(_ text: String? = nil, type: TipsType = .none, time: Double = 2.5, canTouch: Bool = false, _ finishedBlock: (() -> Void)? = nil) {
        Async.main {
            self.view.showTips(text, type: type, time: time, canTouch: canTouch, finishedBlock)
        }
    }
    
    // 用于网络请求：text如果为空则会默认替换为  "服务器开小差了，请稍后再试。"
    func showError(_ text: String? = nil, type: TipsType = .none, _ finishedBlock: (() -> Void)? = nil) {
        self.view.showError(text, type: type, finishedBlock)
    }
}


public class PTHUDProgressView: PKHUDProgressView {
    var title: String?
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        imageView.alpha = 1
        self.imageView.contentMode = .scaleToFill
        self.titleLabel.textColor = UIColor.black
        self.titleLabel.font = UIFont.systemFont(ofSize: 12)
        self.titleLabel.textAlignment = .center
        if title.or("").isEmpty {
            let space: CGFloat = 20.0
            self.imageView.frame = CGRect(x: space, y: space, width: self.width - 2*space, height: self.height - 2*space)
        }else {
            self.imageView.frame = CGRect(x: (self.width - 30)/2, y: 20, width: 30, height: 30)
            self.titleLabel.frame = CGRect(x: 0, y: 67, width: self.width, height: 16)
        }
    }
}


